<?php

namespace app\admin\controller\health\website;

use app\common\controller\Backend;
use app\health\model\HealthWebsiteBanner;
use Exception;
use PDOException;
use think\Db;
use think\exception\ValidateException;

/**
 * 轮播图管理
 * @Author 张旭鹏
 * @DateTime 2023-07-13
 */
class Banner extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model(HealthWebsiteBanner::class);
        $positionMap = [];
        foreach (HealthWebsiteBanner::POSITION_MAP as $k => $v) {
            $positionMap[] = ['name' => $k, 'label' => $v];
        }
        $typeMap = [];
        foreach (HealthWebsiteBanner::TYPE_MAP as $k => $v) {
            $typeMap[] = ['name' => $k, 'label' => $v];
        }
        $this->assignconfig('position_map', $positionMap);
        $this->assignconfig('type_map', $typeMap);
    }

    /**
     * 轮播图列表
     * @Author 张旭鹏
     * @DateTime 2023-07-13
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $nobuildfields = [];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);
            $total = $this->buildSearch()
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->buildSearch()
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return $this->success('操作成功', null, $result);
        }
        $this->assign('title', '轮播图管理');
        return $this->view->fetch();
    }

    protected function buildSearch()
    {
        $model = $this->model;
        if ($this->request->has('position')) {
            $model = $model->where('position', $this->request->param('position'));
        }
        return $this->model;
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $params = json_decode($params['data'], true);
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("添加成功");
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('position', $this->request->param('position', 1));
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = json_decode($params['data'], true);
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("row", $row);
        return $this->view->fetch();
    }

    /**
     * 设置轮播图状态
     * @param [type] $ids
     * @param [type] $status
     * @Author 张旭鹏
     * @DateTime 2023-07-13
     */
    public function setStatus($ids, $status)
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $v->status = $status;
                    $count += $v->save();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
